package com.ruoyi.device.service.impl;

import java.util.List;
import java.util.UUID;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.util.Base64;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.device.mapper.DeviceInfoMapper;
import com.ruoyi.device.domain.DeviceInfo;
import com.ruoyi.device.service.IDeviceInfoService;

/**
 * 设备信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@Service
public class DeviceInfoServiceImpl implements IDeviceInfoService 
{
    @Autowired
    private DeviceInfoMapper deviceInfoMapper;

    /**
     * 查询设备信息
     * 
     * @param deviceId 设备信息主键
     * @return 设备信息
     */
    @Override
    public DeviceInfo selectDeviceInfoByDeviceId(String deviceId)
    {
        return deviceInfoMapper.selectDeviceInfoByDeviceId(deviceId);
    }

    /**
     * 查询设备信息列表
     * 
     * @param deviceInfo 设备信息
     * @return 设备信息
     */
    @Override
    public List<DeviceInfo> selectDeviceInfoList(DeviceInfo deviceInfo)
    {
        return deviceInfoMapper.selectDeviceInfoList(deviceInfo);
    }

    /**
     * 新增设备信息
     * 
     * @param deviceInfo 设备信息
     * @return 结果
     */
    @Override
    public int insertDeviceInfo(DeviceInfo deviceInfo)
    {
        // 如果没有设置设备ID，自动生成
        if (StringUtils.isEmpty(deviceInfo.getDeviceId())) {
            deviceInfo.setDeviceId(generateDeviceId());
        }
        
        // 生成设备密钥
        if (StringUtils.isEmpty(deviceInfo.getSecretKey())) {
            deviceInfo.setSecretKey(UUID.randomUUID().toString().replace("-", ""));
        }
        
        // 设置创建者
        if (StringUtils.isEmpty(deviceInfo.getCreateBy())) {
            deviceInfo.setCreateBy(SecurityUtils.getUsername());
        }
        
        deviceInfo.setCreateTime(DateUtils.getNowDate());
        return deviceInfoMapper.insertDeviceInfo(deviceInfo);
    }

    /**
     * 修改设备信息
     * 
     * @param deviceInfo 设备信息
     * @return 结果
     */
    @Override
    public int updateDeviceInfo(DeviceInfo deviceInfo)
    {
        deviceInfo.setUpdateTime(DateUtils.getNowDate());
        return deviceInfoMapper.updateDeviceInfo(deviceInfo);
    }

    /**
     * 批量删除设备信息
     * 
     * @param deviceIds 需要删除的设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceInfoByDeviceIds(String[] deviceIds)
    {
        return deviceInfoMapper.deleteDeviceInfoByDeviceIds(deviceIds);
    }

    /**
     * 删除设备信息信息
     * 
     * @param deviceId 设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceInfoByDeviceId(String deviceId)
    {
        return deviceInfoMapper.deleteDeviceInfoByDeviceId(deviceId);
    }

    /**
     * 生成WiFi二维码
     * 
     * @param deviceId 设备ID
     * @return 二维码Base64字符串
     */
    @Override
    public String generateQrCode(String deviceId)
    {
        try {
            // 构建二维码内容，包含设备ID等参数
            String qrContent = "https://www.tt-wf.com/wifi?deviceId=" + deviceId + "&timestamp=" + System.currentTimeMillis();
            
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(qrContent, BarcodeFormat.QR_CODE, 200, 200);
            
            BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "PNG", outputStream);
            
            return Base64.getEncoder().encodeToString(outputStream.toByteArray());
        } catch (WriterException | IOException e) {
            throw new RuntimeException("生成二维码失败", e);
        }
    }

    /**
     * 更新设备心跳时间
     * 
     * @param deviceId 设备ID
     * @return 结果
     */
    @Override
    public int updateDeviceHeartbeat(String deviceId)
    {
        return deviceInfoMapper.updateDeviceHeartbeat(deviceId);
    }

    /**
     * 获取设备统计信息
     * 
     * @return 设备统计信息
     */
    @Override
    public DeviceStatistics getDeviceStatistics()
    {
        DeviceStatistics statistics = new DeviceStatistics();
        
        // 在线设备数
        statistics.setOnlineDevices(deviceInfoMapper.countDeviceByStatus(1));
        // 离线设备数
        statistics.setOfflineDevices(deviceInfoMapper.countDeviceByStatus(0));
        // 故障设备数
        statistics.setFaultDevices(deviceInfoMapper.countDeviceByStatus(2));
        // 总设备数
        statistics.setTotalDevices(statistics.getOnlineDevices() + statistics.getOfflineDevices() + statistics.getFaultDevices());
        
        return statistics;
    }

    /**
     * 生成设备ID
     * 
     * @return 设备ID
     */
    private String generateDeviceId() {
        return "DEV" + System.currentTimeMillis() + String.format("%04d", (int)(Math.random() * 10000));
    }
} 